# -*- coding:utf-8 -*-
import uuid
from fastapi import APIRouter, Request, Depends, Query
from core.response import tableinfo, success, fail
from app.service.system import CaptchaService, AuthService, SysClientService
from app.entity.system import AuthData
from core.storage import RedisStorage
from config.app import get_config
from app.annotation import Log, RateLimiter, CacheAble
from core.constants import BusinessType

router = APIRouter()


@router.get("/captcha")
@RateLimiter(key="captcha", period=10, count=10)
async def captcha(req: Request):
    """
    验证码接口 默认算式验证码, 10s 限流 10次
    :param req:
    :return:
    """
    config = get_config()

    if config.CAPTCHA_ENABLE:
        key = str(uuid.uuid4())
        img, code = CaptchaService.generate_captcha(config.CAPTCHA_TYPE, config.CAPTCHA_LENGTH)

        key = str(uuid.uuid4())

        await RedisStorage.set_cache_object(req.app, config.CAPTCHA_PREFIX + key, code, config.CAPTCHA_EXPIRE)

        return success("OK", {"enabled": True, "key": key, "image": img})
    else:
        return success("OK", {"enabled": False})


@router.get("/client/list")
# @CacheAble(expires=3600)
async def getTenantList(req: Request, mService=Depends(SysClientService.instance)):
    """
    获取租户列表
    :return: json_response
    """
    rows = await mService.get_client_list()
    return success("OK", list(rows))


@router.post('/login', summary='登录')
@Log(title="用户登录", log_type='login', business_type=BusinessType.LOGIN)
async def user_login(req: Request, auth: AuthData, mService=Depends(AuthService.instance)):
    """
    用户登录
    :param req:
    :param mService:
    :param auth:
    :return:
    """
    res, token = await mService.login(auth)
    if not res:
        return fail(token)

    return success("OK", {"access_token": token, "refresh_token": ""})


@router.post("/logout")
@Log(title="退出登录", log_type='login', business_type=BusinessType.LOGOUT)
async def logout(req: Request):
    """
    注销登录， 清除token
    :return:
    """
    return success("OK")
